<template>
  <div class="container" style="height: 100vh;width: 300px;padding: 20px;box-sizing: border-box;width: 100%;">
    <header>
      <MBreadcrumb :item="breadcrumbItem" />
    </header>
    <main>
      <div v-for="(obj, index) in MListItem" :key="index">
        <MTitle class="title" :rightIcon="rightIcon">
          <template #left>
            {{ obj.title }}
          </template>
          <template #right>
            <MIcon :src="Edit" class="righticon" @click="update(obj)">
            </MIcon>
            <MIcon :src="Delete" class="righticon" @click="deleteInfo(obj)">
            </MIcon>
          </template>
        </MTitle>
        <MList :item="obj.value"></MList>
      </div>

    </main>
    <footer>
      <MButton @click="showModal = true" v-if="!isDisable">新增</MButton>
    </footer>
    <MModal v-model="showModal" title="新增" :onSubmit="handleSubmit" :onCancel="handleCancel">
      <form>
        <div style="margin: 10px 5px;display: flex;">
          <MLabel for="rulename" style="flex: 1 1 70px;">规则名称:</MLabel>
          <MInput v-model="formData.rulename" id="rulename" required style="flex: 1 1 200px;">
          </MInput>
          <!-- <input v-model="formData.rulename" id="rulename" required> -->
        </div>
        <div style="margin: 10px 5px;display: flex;">
          <MLabel for="ruletype" style="flex: 1 1 70px;">类型:</MLabel>
          <MSelect v-model="formData.ruletype" :options="options" :value="formData.ruletype" id="ruletype" required
            style="flex: 1 1 200px;">
          </MSelect>
        </div>
        <div style="margin: 10px 5px;display: flex;">
          <MLabel for="batchnum" style="flex: 1 1 70px;">批次号:</MLabel>
          <MInput v-model="formData.batchnum" id="batchnum" required style="flex: 1 1 200px;"></MInput>
        </div>
        <div style="margin: 10px 5px;display: flex;">
          <MLabel for="serialnum" style="flex: 1 1 70px;">序列号:</MLabel>
          <MInput v-model="formData.serialnum" id="serialnum" required style="flex: 1 1 200px;" />
        </div>
        <div style="margin: 10px 5px;display: flex;">
          <MLabel for="randomnum" style="flex: 1 1 70px;">随机码长度:</MLabel>
          <MInput type="number" v-model="formData.randomnum" id="randomnum" required style="flex: 1 1 200px;" />
        </div>
      </form>
    </MModal>
    <MMessage v-if="toastVisible" :message="toastMessage" :state="toastState" />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import MBreadcrumb from "../components/MBreadcrumb.vue"
import MTitle from "../components/MTitle.vue"
import MList from "../components/MList.vue"
import MButton from "../components/MButton.vue"
import Edit from "@/resource/edit.png"
import Delete from "@/resource/delete.png"
import MModal from '../components/MModal.vue';
import MInput from "../components/MInput.vue"
import MLabel from "../components/MLabel.vue"
import MSelect from '../components/MSelect.vue';
import axios from "../axios/axios"
import MIcon from "../components/MIcon.vue"
import MMessage from '../components/MMessage.vue';
export default {
  name: "CodeRules1",
  components: {
    MBreadcrumb, MTitle, MList, MButton, MModal, MInput, MLabel, MSelect, MIcon, MMessage
  },

  setup() {
    const userId = ref("")
    const toastVisible = ref(false)
    const toastMessage = ref("")
    const toastState = ref("success")
    const showModal = ref(false);
    const options = [
      { value: '0', text: '产品规则' },
      { value: '1', text: '打包规则' },
    ]
    const breadcrumbItem = ref(
      {
        key: "0",
        title: '赋码管理',
        children: {
          key: "0-0",
          title: '赋码规则',
        }
      })
    //const userId = "12121"
    const MListItem = ref([])
    const MListItem2 = ref([])
    const rightIcon = [Edit, Delete]
    const params = ref("")
    const isDisable = ref(false)
    const isUpdate = ref(false)
    const formData = ref({
      rulename: '',
      ruletype: "0",
      batchnum: '',
      serialnum: '',
      randomnum: '',
    });
    function update(item) {
      formData.value = {
        id: item.id,
        rulename: item.title,
        ruletype: item.type,
        batchnum: (item.value)[0].value,
        serialnum: (item.value)[1].value,
        randomnum: (item.value)[2].value,
      }
      showModal.value = true
      isUpdate.value = true
    }
    function deleteInfo(item) {
      axios.get("/rule/delete?id=" + item.id + "&userId=" + userId.value).then(res => {
        if (res.data.Code === "200") {
          const filteredItems = MListItem.value.filter(i => i.id !== item.id);
          MListItem.value = filteredItems
        }
      })
    }
    const handleCancel = () => {
      formData.value = {
        rulename: '',
        ruletype: "0",
        batchnum: '',
        serialnum: '',
        randomnum: '',
      }
      showModal.value = false
    }
    const handleSubmit = () => {
      if (checkPass(formData.value)) {
        if (!isUpdate.value) {
          axios.post("/rule/insert?userId=" + userId.value, { ...formData.value, trainingid: params.value.get("trainingId"), appid: params.value.get("AppId") }).then(res => {
            const data = MListItem.value
            data.push({
              id: res.data.Data.id,
              title: res.data.Data.rulename,
              type: res.data.Data.ruletype,
              value: [
                {
                  key: 1,
                  field: "类型",
                  value: options[res.data.Data.ruletype].text
                },
                {
                  key: 2,
                  field: "批次号",
                  value: res.data.Data.batchnum
                },
                {
                  key: 3,
                  field: "序列号",
                  value: res.data.Data.serialnum
                },
                {
                  key: 4,
                  field: "随机码长度",
                  value: res.data.Data.randomnum
                }
              ]
            })
            MListItem.value = data

          })
        } else {
          axios.post("/rule/update?userId=" + userId.value, formData.value).then(res => {
            if (res.data.Code === "200") {
              const updatedItems = MListItem.value.map(item => {
                if (item.id === formData.value.id) {
                  return {
                    id: formData.value.id,
                    title: formData.value.rulename,
                    type: formData.value.ruletype,
                    value: [
                      {
                        key: 1,
                        field: "类型",
                        value: options[formData.value.ruletype].text
                      },
                      {
                        key: 2,
                        field: "批次号",
                        value: formData.value.batchnum
                      },
                      {
                        key: 3,
                        field: "序列号",
                        value: formData.value.serialnum
                      },
                      {
                        key: 4,
                        field: "随机码长度",
                        value: formData.value.randomnum
                      }
                    ]
                  };
                }
                return item; // 保持其他元素不变
              });
              MListItem.value = updatedItems
            }
            isUpdate.value = false

          })
        }
        showModal.value = false
        formData.value = {
          rulename: '',
          ruletype: '0',
          batchnum: '',
          serialnum: '',
          randomnum: '',
        }
      }
    };
    const messageShow = (msg, state) => {
      toastMessage.value = msg;
      toastVisible.value = true;
      toastState.value = state
      // 使用 setTimeout 模拟 Toast 组件内部的定时器功能（仅用于演示）
      // 在实际使用中，你应该依赖 Toast 组件内部的定时器
      setTimeout(() => {
        toastVisible.value = false;
      }, 3000); // 与 Toast 组件中的 duration 属性保持一致
    }
    const checkIsNull = (values) => {
      if (values.rulename.length == 0) {
        messageShow("请输入规则名称", "warning")
        return false
      }
      if (values.batchnum.length == 0) {
        messageShow("请输入批次码", "warning")
        return false
      }
      if (values.serialnum.length == 0) {
        messageShow("请输入系列号", "warning")
        return false
      }
      if (values.randomnum.length == 0) {
        messageShow("请输入随机码长度", "warning")
        return false
      }
      return true
    }
    const checkPass = (values) => {
      const checkStr = /^[a-zA-Z0-9]+$/
      //console.log(checkStr.test(values.batchnum), checkStr.test(values.serialnum));

      if (!checkIsNull(values)) {
        return false
      }

      if (values.rulename.length > 20) {
        messageShow("规则名称过长", "warning")
        return false
      }
      if (!(checkStr.test(values.batchnum) && checkStr.test(values.serialnum))) {
        messageShow("批次号和序列号只能输入数字或字母", "warning")
        return false
      }
      if (values.batchnum.length > 10 || values.serialnum.length > 10) {
        messageShow("批次号或序列号长度过长", "warning")
        return false
      }
      if (values.randomnum.length > 6) {
        messageShow("随机码长度过长", "warning")
        return false
      }
      if (!(values.randomnum > 0)) {
        messageShow("随机码长度应大于0", "warning")
        return false
      }
      return true
    }
    onMounted(() => {
      // 获取 URL 参数
      const param = new URLSearchParams(window.location.search);
      params.value = param
      if (param.has('AppId')) {
        axios.get("/rule/select?userId=" + param.get('userId') + "&appId=" + param.get("AppId") + "&trainingId=" + param.get("trainingId")).then(res => {
          if (res.data.Data.length !== 0) {
            const data = []
            res.data.Data.forEach(element => {
              data.push({
                id: element.id,
                title: element.rulename,
                type: element.ruletype,
                value: [
                  {
                    key: 1,
                    field: "类型",
                    value: options[element.ruletype].text
                  },
                  {
                    key: 2,
                    field: "批次号",
                    value: element.batchnum
                  },
                  {
                    key: 3,
                    field: "序列号",
                    value: element.serialnum
                  },
                  {
                    key: 4,
                    field: "随机码长度",
                    value: element.randomnum
                  },

                ]
              })
              MListItem.value = data
            });
          }

        })
      }
      if (param.has('isDisable')) {
        isDisable.value = param.get('isDisable') === "true"
      }
      if (param.has('userId')) {
        userId.value = param.get('userId');
      }
    });
    return {
      breadcrumbItem,
      Edit,
      rightIcon,
      MListItem,
      MListItem2,
      Delete,
      showModal,
      formData,
      handleSubmit,
      update,
      deleteInfo,
      isDisable,
      options,
      handleCancel,
      toastVisible,
      toastMessage,
      toastState
    };
  },
};
</script>

<style scoped>
.title {
  margin-top: 20px;
}

.title1 {
  margin-top: 20px;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

footer {
  text-align: center;
  height: 10%;
}

main {
  flex: 1;
  overflow-y: auto;

}

.righticon {
  margin: 0 0 0 10px;
}
</style>
